package com.speed_run.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.speed_run.global.UserSession;
import com.speed_run.mapper.ExerciseMapper;
import com.speed_run.mapper.UserMapper;
import com.speed_run.model.ExerciseData;
import com.speed_run.service.IUserExerciseData;
import com.speed_run.utils.DateUtils;
import com.speed_run.utils.JwtUtils;
import com.speed_run.utils.ResponseEntity;
import com.speed_run.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class UserExerciseDataImpl implements IUserExerciseData{

    @Autowired
    private ExerciseMapper mapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${config.host}")
    private String host;

    @Override
    public ResponseEntity addData(ExerciseVo vo) {
    	ExerciseData d = null;
    	if(vo.getType() == 0) {
    		ExerciseData entity = vo.getEntity();
    		Map<String, Object> data = mapper.getDataByType(entity.getUserId(), new Date(), 0);
    		if(data == null) {
    			mapper.saveEntity(vo.getEntity());
    		}else {
    			Map<String, Object> _data = new HashMap<>();
    			_data.put("id", data.get("id"));
    			_data.put("kilometre", entity.getKilometre());
    			_data.put("step", entity.getStep());
    			_data.put("second", entity.getMinute());
    			_data.put("calorie", entity.getCalorie());
    			_data.put("date", new Date());
    			mapper.updateData(_data);
    		}
    	}else {
    		if(vo.getType() == 1 || vo.getType() == 3) {
    			d = vo.getEntity();
        		mapper.saveEntity(d);
    		}
    	}
    	JSONObject j = new JSONObject();
    	j.put("id", d==null?-1:d.getId());
        return ResponseEntity.ok("上传数据成功",j);
    }

    @Override
    public ResponseEntity getUserExerData(String token) {
        String userId = JwtUtils.pareseToken(token);
        List<ExerciseSubVo> list = new ArrayList<>();
        //获取当天漫步信息
        for (int i = 0; i < 4; i++) {
            ExerciseSubVo vo = new ExerciseSubVo();
            vo.setCalorie(0);
            vo.setKilometre(0.00f);
            vo.setSecond(0);
            vo.setType(i);
            list.add(vo);
        }
        List<ExerciseSubVo> mList = mapper.getSubVo(userId,getStartTime(),getEndTime());
        List<ExerciseSubVo>  oList = mapper.getSubVo(userId,null,null);
        mList.addAll(oList);
        for (ExerciseSubVo vo: list) {
            for (ExerciseSubVo vo1: mList) {
                if(vo.getType().equals(vo1.getType())){
                    vo.setKilometre(vo1.getKilometre()/100);
                    vo.setCalorie(vo1.getCalorie());
                    vo.setSecond(vo1.getSecond());
                }
            }
        }
        mapper.getSubVo(token,null,null);
        return ResponseEntity.ok("获取运动信息成功",list);
    }

    @Override
    public ResponseEntity getStatisticsData(String token) {
        String userId = JwtUtils.pareseToken(token);
        List<StatisDateVo> kilometre = new ArrayList<>();
        List<StatisDateVo> step = new ArrayList<>();
        List<StatisDateVo> calorie = new ArrayList<>();
        List<StatisInnerVo> detailKilometre = new ArrayList<>();
        List<String> dateList = DateUtils.getPastdays(7);
        List<StatisResultVo> result = mapper.getResult(userId);
        List<StatisInnerVo> _result = mapper.getDetailResult(userId);
        for (int i=0;i<dateList.size();i++) {
            StatisDateVo vo = new StatisDateVo();
          //  StatisInnerVo sVo = new StatisInnerVo();
            vo.setDate(formatterDate(dateList.get(i)));
            vo.setValue(0);
           // sVo.setMinute(0);
           // sVo.setKilometre(0);
            //sVo.setTime(dateList.get(i));
            kilometre.add(vo);
            StatisDateVo vo1 = new StatisDateVo();
            vo1.setDate(formatterDate(dateList.get(i)));
            vo1.setValue(0);
            step.add(vo1);
            StatisDateVo vo2 = new StatisDateVo();
            vo2.setDate(formatterDate(dateList.get(i)));
            vo2.setValue(0);
            calorie.add(vo2);
            //detailKilometre.add(sVo);
            for (StatisResultVo s : result) {
                if(s.getDate().equals(dateList.get(i))){
                    kilometre.get(i).setValue(s.getKilometre());
                    step.get(i).setValue(s.getStep());
                    calorie.get(i).setValue(s.getCalorie());
                  //  detailKilometre.get(i).setKilometre(s.getKilometre());
                //    detailKilometre.get(i).setMinute(s.getMinute());
                }
            }
        }
        for (StatisInnerVo vo:_result) {
            String avatar = userMapper.getUserByUserId(userId).getAvator();
            if(StringUtils.isEmpty(avatar)){
                vo.setAvator("");
            }else {
                vo.setAvator(host+avatar);
            }
        }

        StatisticsVo resutlSvo = new StatisticsVo();
        resutlSvo.setCalorie(calorie);
        resutlSvo.setDetailKilometre(_result);
        resutlSvo.setKilometre(kilometre);
        resutlSvo.setStep(step);

        return ResponseEntity.ok("获取数据成功",resutlSvo);
    }

    @Override
    public ResponseEntity getStatisticsBarData(BarVo vo) {
        String userId =  JwtUtils.pareseToken(vo.getToken());
        Date startDate = new Date(vo.getStartTime());
        Date endDate = new Date(vo.getEndTime());
        BarResultVo _vo =  new BarResultVo();
        List<StatisDateVo> voList= _vo.getBarData();
        List<Map<String, Object>> barList = mapper.getBarData(userId,startDate,endDate);
        Map<String, Object> avgData = mapper.getAvgData(userId,startDate,endDate);
        List<String> dateList = DateUtils.getDateListByTime(vo.getStartTime(),vo.getType());
        if(avgData == null){
            voList = null;
        }else{
            for (String date: dateList) {
                StatisDateVo sVo = new StatisDateVo();
                voList.add(sVo);
                for (Map map: barList) {
                    sVo.setDate(date);
                    if(date.equals(map.get("f_date"))){
                        sVo.setValue(Integer.valueOf(map.get("step").toString()));
                        continue;
                    }
                }
            }
        }
        _vo.setAvgCalorie(avgData == null? "0":avgData.get("avgCalorie").toString());
        _vo.setAvgKilometre(avgData == null? "0":avgData.get("avgKilometre").toString());
        _vo.setAvgNumber("12");
        _vo.setAvgSecond(avgData == null? "0":avgData.get("avgSecond").toString());
        _vo.setAvgStep(avgData == null? "0":avgData.get("avgStep").toString());
        return ResponseEntity.ok("获取数据成功",_vo);
    }


	@Override
	public ResponseEntity exerciseDetailData(Integer page) {
	    PageHelper.startPage(page, 10);
	    List<StatisInnerVo> _result = mapper.getDetailResult(UserSession.get().getUserId());
	    for (StatisInnerVo vo:_result) {
            String avatar = userMapper.getUserByUserId(UserSession.get().getUserId()).getAvator();
            if(StringUtils.isEmpty(avatar)){
                vo.setAvator("");
            }else {
                vo.setAvator(host+avatar);
            }
        }
		return ResponseEntity.ok3("", _result);
	}



    private String formatterDate(String date){
        String[] str =date.split("-");
        return str[1]+"."+str[2];
    }

    private  Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }

    private  Date getEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

}
